package com.ruoyi.workbench.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.workbench.domain.*;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.workbench.dto.IndexMatterRequest;
import com.ruoyi.workbench.dto.OptionUtile;
import com.ruoyi.workbench.dto.RelatedIndicatorOrTaskRequest;
import com.ruoyi.workbench.dto.UsersDTO;
import com.ruoyi.workbench.mapper.*;
import com.ruoyi.workbench.dto.*;
import com.ruoyi.workbench.service.IWorkTaskService;
import com.ruoyi.workbench.service.WorkMatterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 事项(WorkMatter)表服务实现类
 *
 * @author makejava
 * @since 2024-07-04 10:46:30
 */
@Service("workMatterService")
public class WorkMatterServiceImpl implements WorkMatterService {
    @Resource
    private WorkMatterMapper workMatterDao;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Autowired
    private WorkContentMapper workContentMapper;

    @Autowired
    private WorkCollaborationMapper workCollaborationMapper;
    @Resource
    private IWorkTaskService workTaskService;

    @Autowired
    private WorkMatterPracticableMapper workmatterpracticableMapper;

    @Autowired
    private WorkDialogMapper workDialogMapper;

    @Autowired
    private WorkReportMapper workReportMapper;
    @Autowired
    private WorkMatterSummaryMapper workMatterSummaryMapper;

    /**
     * 新增数据
     *
     * @param workMatter 实例对象
     * @return 实例对象
     */
    @Override
    public WorkMatter insert(WorkMatter workMatter) {
        this.workMatterDao.insert(workMatter);
        return workMatter;
    }

    @Override
    public PageInfo<WorkMatter> getIndexList(WorkMatter matter, PageDomain pageDomain) {
        PageHelper.startPage(pageDomain.getPageNum(), pageDomain.getPageSize());

        matter.setStat(0);
        List<WorkMatter> list = workMatterDao.getList(matter);
        PageInfo<WorkMatter> pageInfo = new PageInfo<>(list);

        return pageInfo;
    }

    /**
     * 查询事项列表
     *
     * @param matter 事项
     * @return 集合
     */
    @Override
    @DataScope(deptAlias = "result", userAlias = "result")
    public List<WorkMatter> getDataScopeMatterList(WorkMatter matter)
    {
        Long userId = SecurityUtils.getUserId();
        List<WorkMatter> workMatters = workMatterDao.selectDataScopeMatterList(matter);
        for (WorkMatter workMatter : workMatters) {
            workMatter.setIsLeader(userId == Long.valueOf(workMatter.getMatterResponsibleId()));
            List<WorkDialog> workDialogs = workDialogMapper.selectAllByMatterId(workMatter.getMatterId());
            if (workDialogs.size()>0) {
                workMatter.setDialogStatus(true);
                String dialogContent = "";

                for (WorkDialog workDialog : workDialogs) {// 催办意见
                    if (workDialog.getDialogUserId()!=null) {
                        SysUser sysUser = sysUserMapper.selectUserById(Long.valueOf(workDialog.getDialogUserId()));
                        dialogContent += sysUser.getNickName() + "：" + workDialog.getDialogContent() + "\t\t " + DateUtils.parseDateToStr("yyyy-MM-dd", workDialog.getCreateTime())+"<br/>";

                    }
                }
                workMatter.setDialogContent(dialogContent);

            }else {
                workMatter.setDialogStatus(false);
            }

        }
        return  workMatters;
    }

    /**
     * 通过ID查询单条数据
     *
     * @param matterId 主键
     * @return 实例对象
     */
    @Override
    public WorkMatter queryById(Integer matterId) {
        return this.workMatterDao.queryById(matterId);
    }

    @Override
    public int deleteMatterIds(Long[] matterIds)
    {
        return this.workMatterDao.deleteMatterIds(matterIds);
    }
    /**
     * 修改数据
     *
     * @param workMatter 实例对象
     * @return 实例对象
     */
    @Override
    public WorkMatter update(WorkMatter workMatter) {
        this.workMatterDao.update(workMatter);
        return this.queryById(workMatter.getMatterId());
    }

    /**
     * 通过主键删除数据
     *
     * @param matterId 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Long matterId) {
        return this.workMatterDao.deleteById(matterId) > 0;
    }

    @Override
    public List<UsersDTO> getUsers() {
        return this.workMatterDao.getUsers();
    }

    @Override
    public List<RelatedIndicatorOrTaskRequest> getTargetTasks() {
        return this.workMatterDao.getTargetTasks();
    }

    @Override
    public List<RelatedIndicatorOrTaskRequest> getTasks() {
        return this.workMatterDao.getTasks();
    }

    @Override
    public List<OptionUtile> getSystemManage() {
        return workMatterDao.getSystemManage();
    }

    @Override
    public AjaxResult getMatterList() {
        List<WorkMatter> workMatters = workMatterDao.selectAll();
        workMatters.stream().forEach(workMatter -> {
            String workContentType = workMatter.getWorkContentType();
            if ("0".equals(workContentType)) {
                workContentType = "市场类";
            } else if ("1".equals(workContentType)) {
                workContentType = "非市场类";
            }
            if (!workMatter.getMatterName().contains("（市场类）") && !workMatter.getMatterName().contains("（非市场类）")) {
                workMatter.setMatterName(workMatter.getMatterName() + "（" + workContentType + "）");
            }
        });
        return AjaxResult.success(workMatters);
    }

    @Override
    public AjaxResult getInfo(Integer sid) {
        WorkMatter workMatter = workMatterDao.selectAllByMatterId(sid);
        List<WorkMatterSummary> matterSummaries = workMatterSummaryMapper.selectAllByWorkMatterId(sid);
        if (matterSummaries.size()>0) {
            workMatter.setSummaryDate(matterSummaries.get(0).getSummaryDate());
        }
        String workContentType = workMatter.getWorkContentType();
        if ("0".equals(workContentType)) {
            workContentType = "市场类";
        } else if ("1".equals(workContentType)) {
            workContentType = "非市场类";
            if (!workMatter.getMatterName().contains("（市场类）") && !workMatter.getMatterName().contains("（非市场类）")) {
                workMatter.setMatterName(workMatter.getMatterName() + "（" + workContentType + "）");
            }
        }
        List<WorkContent> workContents = workContentMapper.selectAllByMatterId(sid);

        for(WorkContent workContent : workContents){
            Long workContentId = workContent.getWorkContentId();
            // 协同需求
            List<WorkCollaboration> workCollaborations = workCollaborationMapper.selectAllByMatterIdAndWorkContentId(sid,workContentId);
            workCollaborations.stream().forEach(item -> {
                String collaboratorsId = item.getCollaboratorsId();
                if ( collaboratorsId != null) {
                    String[] collaboratorsIdArr = collaboratorsId.split(",");
                    Long[] collaboratorsIdLongArr = new Long[collaboratorsIdArr.length];
                    for (int i = 0; i < collaboratorsIdArr.length; i++) {
                        collaboratorsIdLongArr[i] = Long.parseLong(collaboratorsIdArr[i]);
                    }

                    item.setCollaboratorsIdList(collaboratorsIdLongArr);


                    StringBuilder names = new StringBuilder();
                    for(String collaboratorsIdStr : collaboratorsIdArr){
                        SysUser sysUser1 = sysUserMapper.selectUserById(Long.valueOf(collaboratorsIdStr));
                        if (sysUser1 != null) {
                            names.append(sysUser1.getNickName()).append(",");
                        }
                    }
                    item.setCollaboratorsName(names.toString());

                }
            });
            workContent.setWorkCollaborationList(workCollaborations);
        }
        // 工作内容
        workMatter.setWorkContentList(workContents);
        if (workMatter.getDeptId() != null) {// 归属部门翻译
            SysDept sysDept = sysDeptMapper.selectDeptById(Long.valueOf(workMatter.getDeptId()));
            workMatter.setDept(sysDept.getDeptName());
        }

        // 超期天数
//        if (workContent.getPlannedCompletionTime() != null) {//超期天数
//            Date plannedCompletionTime = workContent.getPlannedCompletionTime();
//            Date now = new Date();
//            int i = DateUtils.differentDaysByMillisecond(now, plannedCompletionTime);
//            if (i > 0) {
//                workMatter.setOverDueDay(i);
//            }
//        }

        // 事项负责人姓名
        SysUser sysUser = sysUserMapper.selectUserById(Long.valueOf(workMatter.getMatterResponsibleId()));
        if (sysUser != null) {
            workMatter.setMatterResponsibleName(sysUser.getNickName());
        }


        // 催办信息
        List<WorkDialog> workDialogs = workDialogMapper.selectAllByMatterId(sid);
        workDialogs.stream().forEach(item -> {
            if (item.getDialogUserId() != null) {
                SysUser sysUser1 = sysUserMapper.selectUserById(Long.valueOf(item.getDialogUserId()));
                if (sysUser1 != null) {
                    item.setDialogUserName(sysUser1.getNickName());
                }
            }

        });
        // 工作报告
        List<WorkReport> workReports = workReportMapper.selectAllByMatterId(sid);
        workReports.stream().forEach(item -> {
            if (item.getCompileId() != null) {
                SysUser sysUser1 = sysUserMapper.selectUserById(Long.valueOf(item.getCompileId()));
                if (sysUser1 != null) {
                    item.setCompileName(sysUser1.getNickName());
                }

            }
        });
        // 关键节点
        workMatter.setContentAndCollNameList(workContentMapper.getContentAndCollName(sid));
        workMatter.setWorkDialogList(workDialogs);
        workMatter.setWorkMatterPracticableList(workmatterpracticableMapper.selectAllByMatterId(sid));
        workMatter.setWorkReportList(workReports);
        return AjaxResult.success(workMatter);
    }

    @Override
    public void updateTaskStat(Integer relatedIndicatorOrTaskId) {
        workMatterDao.updateTaskStat(relatedIndicatorOrTaskId);
    }

    @Override
    public List<WorkReport> getReports(String matterId) {
        return workMatterDao.getReports(matterId);
    }

    @Override
    public PageInfo<WorkMatter> getMyMatterPage(JSONObject params) {
        params.put("matterResponsibleId",SecurityUtils.getUserId());
        PageHelper.startPage(params.getInteger("pageNum"), params.getInteger("pageSize"));
        List<WorkMatter> workMatters = workMatterDao.queryAll(params);
        return new PageInfo<>(workMatters);
    }

    @Override
    public void matterClaim(Map<String, Object> params) {
        workMatterDao.updateEm4ByMatterId(params);
    }

    @Override
    public PageInfo<WorkTask> listTask(ListTaskRequest request, PageDomain pageDomain) {

        PageHelper.startPage(pageDomain.getPageNum(), pageDomain.getPageSize());

        List<WorkTask> list = workMatterDao.listTask(request);
        PageInfo<WorkTask> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public boolean taskClaim(Integer taskId) {

        WorkTask workTask = workTaskService.selectWorkTaskByTaskId(taskId);
        String taskStatus = workTask.getTaskStatus();
        if (taskStatus != null && !"2".equals(taskStatus)) {
            return false;
        }
        workTask.setTaskStatus("6");

        int i = workTaskService.updateWorkTask(workTask);

        return i > 0;
    }

    @Override
    public PageInfo<WorkMatter> dialogList(WorkMatter matter, PageDomain pageDomain) {
        PageHelper.startPage(pageDomain.getPageNum(), pageDomain.getPageSize());

        matter.setStat(0);
        List<WorkMatter> list = workMatterDao.dialogList(matter);
        PageInfo<WorkMatter> pageInfo = new PageInfo<>(list);

        return pageInfo;
    }

    @Override
    public void updteFollowed(WorkMatter matter) {
        Boolean isFollowed = matter.getIsFollowed();
        Integer matterId = matter.getMatterId();
        Long userId = SecurityUtils.getUserId();
        if (isFollowed == null || matterId == null) {
            throw new IllegalArgumentException("isFollowed 和 matterId 都不能为空");
        }
        if (isFollowed) {
            // 添加关注
            workMatterDao.addFollowed(userId, matterId);
        } else {
            // 取消关注
            workMatterDao.delFollowed(userId, matterId);
        }
    }

    @Override
    public List<Map<String, Object>> getPracticables(String matterId) {
        return workMatterDao.getPracticables(matterId);
    }

    @Override
    public void updateDialog(String dialogId, String dialogContent) {
        workMatterDao.updateDialog(dialogId, dialogContent);
    }
}
